<template>
  <el-row class="NoticeDrawer">
    <commonDrawer
      :title="drawerType==='edit'?'编辑公告':'新增公告'"
      :drawer="drawer"
      :size="'650px'"
      @closeDraw="closeDraw"
      :isShowMoreBtn="false"
    >
      <template slot="column">
        <el-form
          class="m7-form drawerForm"
          ref="activePostForm"
          :model="activePostForm"
          :rules="rules"
          label-position="top"
        >
          <el-form-item label="公告标题" prop="title">
            <el-input
              v-model="activePostForm.title"
              placeholder="至多50个汉字"
              clearable
              maxlength="50"
              type="textarea"
              autosize
              @input="replaceEnter"
              style="vertical-align:top"
            />
          </el-form-item>
          <el-form-item label="公告内容">
            <span slot="label"><span style="color: #F56C6C;margin-right:4px">*</span>公告内容</span>
            <Editor ref="editor"></Editor>
            <Upload ref="upload"></Upload>
          </el-form-item>
          <el-form-item label="公示期">
            <el-radio-group v-model="showTime">
              <el-radio v-for="item in showTimeLabel" :key="item.label" :label="item.label">{{item.name}}</el-radio>
            </el-radio-group>
            <el-input v-model.number="customTime" v-if="showTime==4" class="customerTime" @change="changeCustomTime">
              <template slot="append">天</template>
            </el-input>
          </el-form-item>
          <el-form-item label="公示级别" prop="level">
            <el-radio-group v-model="activePostForm.level">
              <el-radio label="common">普通</el-radio>
              <el-radio label="import">重要</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="公示范围">
            <span slot="label"><span style="color: #F56C6C;margin-right:4px">*</span>公示范围</span>
            <div class="visiblePersonnelTransfer">
              <tree-transfer
                height="400px"
                mode="transfer"
                :from_data="transferFromData"
                :to_data="visiblePersonnel"
                :defaultProps="{ label: 'label' }"
                :title="['未选人员', '已选人员']"
                :button_text="['加入选项', '移出选项']"
                placeholder="请输入角色/技能组/座席/部门"
                :high-light="true"
                :transferOpenNode="false"
                :accordion="true"
                @add-btn="add"
                filter
                :renderContentLeft="renderContent"
                :renderContentRight="renderContent"
              ></tree-transfer>
            </div>
          </el-form-item>
        </el-form>
        <div class="publicBtn">
          <el-button size="mini" @click="save" :loading="saveLoading">保存，暂不发布</el-button>
          <el-button size="mini" type="primary" @click="publish" :loading="publishLoading">立即发布</el-button>
        </div>
      </template>
    </commonDrawer>
  </el-row>
</template>

<script lang="tsx">
import { Component, Prop, Vue, Ref, Watch } from 'vue-property-decorator';
import treeTransfer from 'el-tree-transfer';
import commonDrawer from '@/common/views/drawer/index.vue';
import { deepClone, commonAction } from '@/utils/common';
import { renderTree } from './notice'
import Editor from './editor.vue'
import Upload from './upload.vue'
@Component({
  name: 'NoticeDrawer',
  components: {
    commonDrawer,
    treeTransfer,
    Editor,
    Upload
  }
})
export default class NoticeDrawer extends Vue {
  @Ref() private readonly editor: any
  @Ref() private readonly upload: any
  private $message: any
  @Prop(Object) public postForm!: any;
  @Prop({ default: 'add' }) private drawerType!: string;
  private drawer: boolean = false;
  private activePostForm: any = {};
  // 公示范围
  private transferFromData: any = [];
  private visiblePersonnel: any = [];
  // 公示期
  private showTime: number = 0
  private customTime: any = ''
  private saveLoading: boolean = false
  private publishLoading: boolean = false
  private showTimeLabel: object[] = [
    {
      label: 0,
      name: '1天'
    },
    {
      label: 1,
      name: '3天'
    },
    {
      label: 2,
      name: '1周'
    },
    {
      label: 3,
      name: '2周'
    },
    {
      label: 4,
      name: '自定义时间'
    }
  ]

  private rules: object = {
    title: [{ required: true, message: '请输入公告标题', trigger: 'blur' }]
  }

  private renderContent (h: any, { data }): any {
    return <div class='custom-tree-node' style='max-width:150px;overflow:hidden;text-overflow:ellipsis' title={data.label}><span>{data.label}</span></div>
  }

  private replaceEnter (value) {
    value = value.replace(/[\n\r]/g, '')
    this.$set(this.activePostForm, 'title', value)
  }

  // 渲染公示范围
  private async renderFromAndToData () {
    const data = await renderTree(this.postForm.showScope)
    this.transferFromData = data.transferFromData;
    this.visiblePersonnel = data.visiblePersonnel;
    this.transferFromData = this.transferFromData.filter(v => v.children.length > 0)
    this.visiblePersonnel = this.visiblePersonnel.filter(v => v.children.length > 0);
  }

  private changeCustomTime (val) {
    if (/^[\d.]+$/.test(val)) {
      const newval = Math.floor(val)
      this.customTime = newval
    } else {
      this.customTime = ''
    }
  }

  private openDraw () {
    this.drawer = true;
    this.$nextTick(() => {
      this.activePostForm = deepClone(this.postForm);
      (this as any).$getCache('/base/action/general/cache/query', ['roleList', 'queueList', 'userList'], true).then((data: any) => {
        this.renderFromAndToData();
      })
      this.upload.createUpload(this.activePostForm.attachs)
      this.editor.createEdit(this.activePostForm.content)
      const showDays = this.activePostForm.showDays
      if (showDays.type === 'system') {
        if (showDays.value === 1) {
          this.showTime = 0
        } else if (showDays.value === 3) {
          this.showTime = 1
        } else if (showDays.value === 7) {
          this.showTime = 2
        } else if (showDays.value === 14) {
          this.showTime = 3
        }
      } else if (showDays.type === 'custom') {
        this.showTime = 4
        this.customTime = showDays.value
      }
    })
  }

  @Watch('$route')
  public close () {
    this.drawer = false;
  }

  private closeDraw () {
    (this as any).$refs.activePostForm.clearValidate();
    this.drawer = false;
    this.transferFromData = []
    this.visiblePersonnel = []
    this.showTime = 0
    this.customTime = ''
    this.upload.destoryUpload()
    this.editor.destoryEditor();
    this.saveLoading = false
    this.publishLoading = false;
    (this.$refs.activePostForm as any).$el.scrollTop = 0
  }

  // 处理表单数据
  private parseData () {
    let res: any = {
      status: 0,
      data: null
    };
    (this as any).$refs.activePostForm.validate((valid) => {
      if (valid) {
        if (this.editor.content.trim() === '') {
          this.$message.error('请填写公告内容！')
          return res
        }
        if (this.showTime === 4 && !this.customTime) {
          this.$message.error('请填写正确的自定义公示期！')
          return res
        }
        const visibleRole = this.visiblePersonnel.find(v => v.field === 'role')
        const visibleQueue = this.visiblePersonnel.find(v => v.field === 'queue')
        const visibleAgent = this.visiblePersonnel.find(v => v.field === 'user')
        const visibleDept = this.visiblePersonnel.find(v => v.field === 'dept')
        const showScope: any = {
          role: visibleRole ? visibleRole.children.map(v => v.id) : [],
          queue: visibleQueue ? visibleQueue.children.map(v => v.id) : [],
          user: visibleAgent ? visibleAgent.children.map(v => v.id) : [],
          dept: visibleDept ? visibleDept.children.map(v => v.id) : []
        }
        if (showScope.role.length === 0 && showScope.queue.length === 0 && showScope.user.length === 0 && showScope.dept.length === 0) {
          this.$message.error('请选择公示范围！')
          return res
        }
        const params: any = {
          title: this.activePostForm.title,
          level: this.activePostForm.level,
          content: this.editor.content,
          attachs: this.upload.attachsObj,
          showScope: {
            role: showScope.role.join(','),
            queue: showScope.queue.join(','),
            user: showScope.user.join(','),
            dept: showScope.dept.join(',')
          }
        }
        const showDays = {
          type: 'system',
          value: 0
        }
        switch (this.showTime) {
          case 0:
            showDays.value = 1
            break
          case 1:
            showDays.value = 3
            break
          case 2:
            showDays.value = 7
            break
          case 3:
            showDays.value = 14
            break
          case 4:
            showDays.value = this.customTime
            showDays.type = 'custom'
        }
        params.showDays = showDays
        let url = '/base/action/notice/create'
        if (this.drawerType === 'edit') {
          params._id = this.activePostForm._id
          url = '/base/action/notice/update'
        }
        res = {
          status: 1,
          data: params,
          url
        }
      }
    })
    return res
  }

  // 保存但不发布
  private async save () {
    if (this.publishLoading) {
      return
    }
    const { status, data, url } = this.parseData()
    if (status === 0) {
      return
    }
    const params = { url, method: 'POST', data: { ...data, status: 'save' } }
    this.saveLoading = true
    try {
      const result: any = await commonAction(params)
      if (result.success) {
        this.$message.success('保存成功')
        this.closeDraw()
        this.$emit('rederData', 'save');
      }
    } finally {
      this.saveLoading = false
    }
  }

  // 发布
  private async publish () {
    if (this.saveLoading) {
      return
    }
    const { status, data, url } = this.parseData()
    if (status === 0) {
      return
    }
    const params = { url, method: 'POST', data: { ...data, status: 'publish' } }
    this.publishLoading = true
    try {
      const result: any = await commonAction(params)
      if (result.success) {
        this.$message.success('发布成功')
        this.closeDraw()
        this.$emit('rederData', 'publish');
      }
    } finally {
      this.publishLoading = false
    }
  }
}
</script>

<style lang="stylus" scoped>
.NoticeDrawer
  .drawerForm
    margin-bottom 55px
  .visiblePersonnelTransfer
    & >>> .wl-transfer .transfer-title
      font-size 12px
    & >>> .wl-transfer .transfer-main
      overflow hidden
    & >>> .wl-transfer .el-tree
      height calc(100% - 50px)
      // border 1px solid red
      overflow-y auto
    & >>> .custom-tree-node
      font-size 12px
  #NoticeEditor
    margin-bottom 10px
  .publicBtn
    width calc(100% - 48px)
    position absolute
    bottom 0px
    height 56px
    line-height 56px
    background #fff
    text-align right
    z-index 100
  .customerTime
    width: 180px;
    float: right;
    margin-top: 5px;
</style>
